import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import { useDark, useToggle } from '@vueuse/core'

export type ThemeType = 'light' | 'dark'

export const useTheme = defineStore('theme', () => {
  const isDark = useDark()
  const toggleDark = useToggle(isDark)

  const currentTheme = ref<ThemeType>(isDark.value ? 'dark' : 'light')

  watch(isDark, (newVal) => {
    currentTheme.value = newVal ? 'dark' : 'light'
    try {
      localStorage.setItem('theme', currentTheme.value)
    } catch (e) {
      console.error('保存主题失败:', e)
    }
  })

  const toggleTheme = (theme?: ThemeType) => {
    if (theme) {
      currentTheme.value = theme
      isDark.value = theme === 'dark'
    } else {
      toggleDark()
    }
  }

  const initTheme = () => {
    const savedTheme = localStorage.getItem('theme')
    if (savedTheme) {
      toggleTheme(savedTheme as ThemeType)
    }
  }

  return {
    currentTheme,
    isDark,
    toggleTheme,
    initTheme,
  }
})
